import axios, { Method, AxiosRequestConfig } from "axios";
import axiosRetry from "axios-retry";
import { navigate } from "~/router/navigation";
import { appStore, userStore } from "~/store";
import { Storage, RecordKeys } from "~/store";

interface _AxiosRequestConfig extends AxiosRequestConfig {
    isMsg?: boolean;
}

const instance = axios.create({
    timeout: 6000,
    headers: {
        'Accept': 'application/json',
        'Content-Type': 'multipart/form-data',
        'Connection': 'keep-alive'
    },
});

// 仅添加重试机制
axiosRetry(instance, {
    retries: 3,
    retryDelay: (retryCount) => retryCount * 1000,
    retryCondition: (error) => axiosRetry.isNetworkError(error) || error.response?.status === 404
});

interface ResultData<T> {
    code: number | string;
    data: T;
    msg: string;
    [k: string]: any;
}

function _request<T>(method: Method, url: string, config: any) {
    return new Promise<T>(async (resolve, reject) => {
        const userInfo = await Storage.getItem(RecordKeys.me) || {};
        const { isMsg = true, ...arg } = config || {};
        arg.data = arg.data || {};
        arg.params = arg.params || {};
        if (method == 'GET') {
            arg.params.armariumScienceSession = userInfo.token;
        } else {
            arg.data.armariumScienceSession = userInfo.token;
        }
        instance
            .request({
                method,
                url,
                ...arg,
            })
            .then((response: any) => {
                if (response.data.code == 500 && response.data.msg == '用户不存在') {
                    userStore.signOut()
                    Toast.show({ content: appStore.app.language == 'zh' ? "检测到账号在其他设备登录，请重新登录。" : "Account logged in on another device. Please re-login." })
                    navigate('LoginByEmail')
                } else {
                    resolve(response.data);
                }
            })
            .catch((error) => {
                let message = '未知错误';
                if (error.code === 'ECONNABORTED') {
                    message = '请求超时，请稍后重试';
                } else if (error.message === 'Network Error') {
                    message = '网络错误，请检查您的网络连接';
                } else if (error.response) {
                    // 服务器返回了响应，但状态码不是 2xx
                    const status = error.response.status;
                    console.error("请求的错误地址", url, arg)
                    switch (status) {
                        case 400:
                            message = '请求错误';
                            break;
                        case 401:
                            message = '未授权，请登录';
                            break;
                        case 403:
                            message = '拒绝访问';
                            break;
                        case 404:
                            message = '请求地址不存在';
                            break;
                        case 500:
                            message = '服务器内部错误';
                            break;
                        default:
                            message = `连接错误：${status}`;
                    }
                } else if (axios.isCancel(error)) {
                    message = '请求已取消';
                }
                // Notice.show(message, 'error')
                reject(error);
            });
    });
}

export const request = {
    get: (url = "", config = {}) => _request("GET", url, config),
    delete: (url = "", config = {}) => _request("DELETE", url, config),
    post: (url = "", config = {}) => _request("POST", url, config),
    put: (url = "", config = {}) => _request("PUT", url, config),
};